package org.grayrabbit.cms.plugin;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

/**
 * @author sys53
 * @version 1.0
 * @created 06-一月-2012 16:36:15
 */
public class FilePluginJar implements PluginJar {

	private final File jarFile;

	public FilePluginJar(File jarFile) {
		this.jarFile = jarFile;
	}

	/**
	 * 
	 * @param fileName
	 * @throws PluginParseException
	 */
	public InputStream getFile(String fileName) throws PluginParseException {
		JarFile jar;
		try {
			jar = new JarFile(this.jarFile);
		} catch (IOException e) {
			throw new PluginParseException("Cannot open JAR file for reading: "
					+ this.jarFile, e);
		}

		ZipEntry entry = jar.getEntry(fileName);
		if (entry == null) {
			throw new PluginParseException("File " + fileName
					+ " not found in plugin JAR [" + this.jarFile + "]");
		}
		InputStream descriptorStream;
		try {
			descriptorStream = new BufferedInputStream(
					jar.getInputStream(entry)) {
				public void close() throws IOException {
					super.close();
				}
			};
		} catch (IOException e) {
			throw new PluginParseException("Cannot retrieve " + fileName
					+ " from plugin JAR [" + this.jarFile + "]", e);
		}
		return descriptorStream;
	}

	public String getFileName() {
		return this.jarFile.getName();
	}

	public InputStream getInputStream() {
		try{
			return new BufferedInputStream(new FileInputStream(this.jarFile));
		}catch(FileNotFoundException e){
			throw new RuntimeException("Could not open JAR file for reading: " + this.jarFile, e);
		}
	}

}